package com.example.demo.IO;

import com.xiaoleilu.hutool.lang.Base64;
import org.apache.tomcat.util.bcel.classfile.Constant;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @Author: xiatian
 * @CreateTime: 2021/12/22 3:18 下午
 * @Description:
 */
public class TestImg {

    public static void main(String[] args) throws IOException {
        String imgFile = "/Users/xiatian/Pictures/timg.jpeg";
        String strImg = GetImageStr(imgFile);
        System.out.println(strImg);
        System.out.println("图片base64:" + strImg.getBytes().length);

        // 使用指定的 charsetName，通过解码字节将缓冲区内容转换为字符串
        System.out.println("压缩后的大小："+Util.zipString(strImg).getBytes().length);

    }

    /**
     * 压缩字符串,默认梳utf-8
     *
     * @param text
     * @return
     */
    public static String zipBase64(String text) {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            try (DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(out)) {
                deflaterOutputStream.write(text.getBytes());
            }
            return out.toString();
        } catch (IOException e) {

        }
        return null;
    }

    //图片转化成base64字符串
    public static String GetImageStr(String imgFile) {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        return new String(Base64.encode(data));
    }
}

